package com.qk.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.Response.PageResult;
import com.qk.dto.ActivityPageDTO;
import com.qk.entity.Activity;
import com.qk.mapper.ActivityMapper;
import com.qk.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Override
    public PageResult<Activity> getActivities(ActivityPageDTO activityPageDTO) {
        //参数校验
        activityPageDTO.checkPageParam();
        PageHelper.startPage(activityPageDTO.getPage(),activityPageDTO.getPageSize());
        List< Activity> activities = activityMapper.selectPageActivities(activityPageDTO);
        PageResult<Activity> pageResult = new PageResult<>();
        PageInfo<Activity> activityPageInfo = new PageInfo<>(activities);
        pageResult.setTotal(activityPageInfo.getTotal());
        pageResult.setRows(activityPageInfo.getList());
        return pageResult;
    }

    @Override
    public void addActivity(Activity activity) {
        //参数校验
        // 在 service 层或 controller 层添加校验
        if (activity.getName() == null || activity.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("活动名称不能为空");
        }
        if (Objects.isNull(activity)) {
            throw new RuntimeException("参数不能为空");
        }
        activity.setUpdateTime(LocalDateTime.now());
        activity.setCreateTime(LocalDateTime.now());
        activityMapper.addActivity(activity);
    }

    @Override
    public void deleteActivityById(Integer id) {
        //参数校验
        if (id == null || id < 1) {
            throw new RuntimeException("参数不能为空");
        }
        activityMapper.deleteActivityById(id);
    }

    @Override
    public Activity selectActivityById(Integer id) {
        //参数校验
        if (id == null || id < 1) {
            throw new RuntimeException("参数不能为空");
        }
        return activityMapper.selectActivityById(id);
    }

    @Override
    public void updateActivity(Activity activity) {
        //参数校验
        if (Objects.isNull(activity)) {
            throw new RuntimeException("参数不能为空");
        }
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.updateActivity(activity);
    }
}
